package com.sky.controller.user;

import com.sky.context.BaseContext;
import com.sky.entity.AddressBook;
import com.sky.result.Result;
import com.sky.service.AdressBookService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@Api("地址管理")
@RequestMapping("/user/addressBook")
@Slf4j
public class AddressController {

    @Autowired
    private AdressBookService adressBookService;

    @ApiOperation("新增地址")
    @PostMapping
    public  Result save(@RequestBody AddressBook addressBook) {
        log.info("新增地址成功");
        adressBookService.save(addressBook);
        return Result.success();
    }

    @ApiOperation("根据id删除地址")
    @DeleteMapping()
    public Result deleteById( Long id) {
        log.info("删除地址");
        adressBookService.deleteById(id);
        return Result.success();
    }

    @ApiOperation("查询默认地址")
    @GetMapping("/default")
    public Result<AddressBook> getDefault() {
        log.info("查询默认地址");
        AddressBook addressBook = adressBookService.getDefault();
        if (addressBook != null) {
            return Result.success(addressBook);
        }
        return Result.error("没有找到该对象");
    }

    @GetMapping("/list")
    @ApiOperation("查询地址")
    public Result<List<AddressBook>> list()
    {
        log.info("查询地址");
        Long currentId = BaseContext.getCurrentId();
        List<AddressBook> list = adressBookService.list(currentId);
        return Result.success(list);
    }


    @PutMapping
    @ApiOperation("修改地址")
    public Result update(@RequestBody AddressBook addressBook)
    {
        log.info("修改地址");
        adressBookService.update(addressBook);
        return Result.success();
    }

    @ApiOperation("根据id查询地址")
    @GetMapping("{id}")
    public Result<AddressBook> getById(@PathVariable Long id) {
        log.info("根据id查询地址");
        AddressBook addressBook = adressBookService.getById(id);
        if (addressBook != null) {
            return Result.success(addressBook);
        }
        return Result.error("没有找到该对象");
    }

    @ApiOperation("设置默认地址")
    @PutMapping("/default")
    public Result<AddressBook> setDefault(@RequestBody AddressBook addressBook) {
        log.info("设置默认地址");
        addressBook.setIsDefault(1);
        adressBookService.setDefault(addressBook);
        return Result.success(addressBook);
    }

}
